package com.gugu.procedure.service;

import com.alibaba.druid.support.json.JSONUtils;
import com.gugu.procedure.bean.Production;
import com.gugu.procedure.dao.ProductionDao;
import com.gugu.procedure.exceptions.BusinessException;
import com.gugu.procedure.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class ProductionService {

    @Autowired
    private ProductionDao productionDao;

    public Production findProductionByOrderNoAndSpecs(String orderNo, String specs) {
        return productionDao.findTopByOrderNoAndSpecs(orderNo, specs);
    }

    public List <String> productions(String orderNo, String specs) {
        Production production = findProductionByOrderNoAndSpecs(orderNo, specs);
        if (Objects.isNull(production)) {
            throw new BusinessException("请检查订单参数表是否上传");
        }
        List <String> list = (List) JSONUtils.parse(production.getProcedures());
        return list;
    }

    //查询某个产品的第一个的一个工序
    public String firstProduction(String orderNo, String specs) {
        Production production = findProductionByOrderNoAndSpecs(orderNo, specs);
        if (Objects.isNull(production) || StringUtil.isEmpty(production.getProcedures())) {
            throw new BusinessException("请检查订单参数表是否上传");
        }
        List <String> list = (List) JSONUtils.parse(production.getProcedures());
        return list.get(0);
    }


    //查询某个产品的最后的一个工序
    public String finalProduction(String orderNo, String specs) {
        Production production = findProductionByOrderNoAndSpecs(orderNo, specs);
        if (Objects.isNull(production) || StringUtil.isEmpty(production.getProcedures())) {
            throw new BusinessException("请检查订单参数表是否上传");
        }
        List <String> list = (List) JSONUtils.parse(production.getProcedures());
        return list.get(list.size() - 1);
    }


    public String lastProduction(String orderNo, String specs, String production) {
        List <String> list = productions(orderNo, specs);
        for (int i = 0; i < list.size(); i++) {
            if (StringUtil.equals(list.get(i), production)) {
                if (i != 0) {
                    return list.get(i - 1);
                } else {
                    return list.get(0);
                }
            }
        }
        return "";
    }

}
